package ti.ml.car;

import algo.Graph;
import algo.Node;
import algo.astar.AStarAlgorithm;
import algo.dijkstra.DijkstrasAlgorithm;
import algo.dijkstra.Transformer;
import gameDump.Board;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import ti.ml.car.domain.Controller;

public class Map extends javax.swing.JPanel implements Runnable {

    /**
     * Creates new form Map
     */
    Thread animator;
    private Car car;
    private Road road;
    private Controller c;

    public Map() {
        //initComponents();
        road = new Road();
        car = new Car(road);
        setBackground(Color.WHITE);
        setFocusable(true);
        setDoubleBuffered(true);
        c = Controller.getIntance();
    }

    public Car getCar() {
        return car;
    }

    public Road getRoad() {
        return road;
    }

    public void resetMap() {
        road = new Road();
        car = new Car(road);
    }

    @Override
    public void addNotify() {
        super.addNotify();
        animator = new Thread(this);
        animator.start();
    }

    public Thread getAnimator() {
        return animator;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;

        road.DrawMaze(g2d);
        g2d.drawImage(car.getImage(), car.getX(), car.getY(), this);
    }

    public void cycle() {
        car.move();
        repaint();
    }

    //dijkstra algoritme om route te berekenen:
    public void followRoute(int target) {
        int carPosition = car.getPos();
        Graph graph = Transformer.transformToGraph(road.getScreenData());
        DijkstrasAlgorithm dijkstra = new DijkstrasAlgorithm(graph, new Node(carPosition));

        try {
            if (CheckValidTarget(target)) {
                road.leveldata2[target][4] = 3;

                dijkstra.execute(new Node(target));
                LinkedList<Node> path = dijkstra.getPath(new Node(target));
                printRoute(path);

                long time = dijkstra.getAlgorithmTime();
                AddTimeToLog(time);
            } else {
                throw new Exception();
            }
        } catch (Exception e) {
            c.appendTxtLog("Not a valid target");
        }
    }

    //A* algoritme gebruiken om de route te berekenen
    public void followAStarRoute(int target) {
        int[][][] graph = Transformer.transformTo2DArray(road.getScreenData());
        int carPosition = car.getPos();

        try {
            if (CheckValidTarget(target)) {
                road.leveldata2[target][4] = 3;
//                c.appendTxtLog(Transformer.transformGraphPointTo2D(carPosition)[0] + " " + Transformer.transformGraphPointTo2D(carPosition)[1]);

                AStarAlgorithm aStar = new AStarAlgorithm(graph, new Node(carPosition),
                        new Node(target));
                List<Node> path = aStar.searchPath();
                printRoute(path);

                long time = aStar.getAlgorithmTime();
                AddTimeToLog(time);
            } else {
                throw new Exception();
            }
        } catch (Exception e) {
            c.appendTxtLog("Not a valid target");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
        while (true) {
            cycle();
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void printRoute(List<Node> path) {
        Route r = new Route(car, path);
        Thread t = new Thread(r);
        t.start();
    }

    private void AddTimeToLog(long time) {
        DateFormat formate = new SimpleDateFormat("ss:SS");
        c.appendTxtLog("The algoritme took: " + formate
                .format(new Date(time)) + " miliseconds");
    }

    private boolean CheckValidTarget(int target) {
        return (road.leveldata2[target][4] == 0 || road.leveldata2[target][4] == 3);
    }
}